package com.zcoj.security.service.impl;

import com.alibaba.fastjson.JSON;
import com.zcoj.core.model.ApiResponse;
import com.zcoj.pojo.Dto.User;
import com.zcoj.security.dto.LoginUser;
import com.zcoj.security.service.LoginServcie;
import com.zcoj.service.RoleService;
import com.zcoj.service.UserService;
import com.zcoj.util.JwtUtil;
import com.zcoj.util.RedisCaches;
import com.zcoj.wx.pojo.WxQrCode;
import com.zcoj.wx.service.WxQrCodeService;
import com.zcoj.wx.service.WxUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LoginUserImpl implements LoginServcie {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private WxQrCodeService wxQrCodeService;


    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisCaches redisCaches;


    @Override
    public ApiResponse loginUsernamePassword(User user) {
        // AuthenticationManager的authenticate方法进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 如果认证没通过，给出对应提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("认证失败！");
        }
        // 如果认证通过了，使用UUID(用户ID)生成JWT
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        // 把完整的用户信息存入redis
        String uuid = JwtUtil.getUUID();
        String jwt = JwtUtil.createJWT(uuid);
        loginUser.setUuid(uuid);
        redisCaches.setCacheObject("login_" + uuid, JSON.toJSONString(loginUser),12, TimeUnit.HOURS);
        //用户信息 去密码
        user.setPassword("");
        // 把token响应给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", jwt);
        map.put("userinfo",user);
        if(loginUser.getPermission().size()!=0){
            map.put("permission",loginUser.getPermission().get(0));
        }
        return ApiResponse.success( "登录成功！", JSON.toJSON(map));
    }

    @Override
    public ApiResponse loginUserByWxTicket(String ticket) {
        WxQrCode wxQrCodeByTicket = wxQrCodeService.getWxQrCodeByTicket(ticket);
        log.info("wxQrCodeByTicket:{}",wxQrCodeByTicket);
        if(Objects.nonNull(wxQrCodeByTicket)){
            String openId = wxQrCodeByTicket.getOpenId();
            //已经处理
            if (wxQrCodeByTicket.getIsPass().equals(1)){
                Integer uid = wxUserService.checkWxOpenId(openId);
                User user = userService.findById(uid);
                if(Objects.isNull(user)){
                    return ApiResponse.failed("当前用户未绑定系统用户");
                }else {
                    List<String> list=roleService.findByUserId(user.getId());
                    // 把数据封装成LoginUser对象返回
                    LoginUser loginUser = new LoginUser(user.getId(), user.getUsername(), "", user.getRealname(), list);
                    String uuid = JwtUtil.getUUID();
                    String jwt = JwtUtil.createJWT(uuid);
                    loginUser.setUuid(uuid);
                    redisCaches.setCacheObject("login_" + uuid, JSON.toJSONString(loginUser),12, TimeUnit.HOURS);
                    //用户信息 去密码
                    user.setPassword("");
                    // 把token响应给前端
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("token", jwt);
                    map.put("userinfo",user);
                    if(loginUser.getPermission().size()!=0){
                        map.put("permission",loginUser.getPermission().get(0));
                    }
                    map.put("WxQrCode",wxQrCodeByTicket);
                    return ApiResponse.success( "登录成功！", JSON.toJSON(map));
                }
            }else if (wxQrCodeByTicket.getIsPass().equals(0)){
                Integer uid = wxUserService.checkWxOpenId(openId);
                User user = userService.findById(uid);
                if(Objects.isNull(user)&&wxQrCodeByTicket.getIsUsed().equals(1)){
                    return ApiResponse.success("当前用户未绑定系统用户",wxQrCodeByTicket);
                }
                if (wxQrCodeByTicket.getIsExpire().equals(1)){
                    return ApiResponse.success("ticket到期",wxQrCodeByTicket);
                }
            }else if (wxQrCodeByTicket.getIsPass().equals(-1)){
                return ApiResponse.success(null);
            }
        }

        return ApiResponse.failed("未知错误");
    }

    @Override
    public ApiResponse logout() {
        // 获取SecurityContextHolder中的用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String uuid = loginUser.getUuid();
        // 删除redis中的值
        redisCaches.deleteObject("login_" + uuid);
        return ApiResponse.success("退出成功",null);
    }
}
